package com.info.factory.db;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SkillFactoryDbHelper extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
	public static final String TABLE_NAME = "skill";
	//private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + "(_ID integer primary key autoincrement);";
	
	private Context context;
	
	private SQLiteDatabase database;
		
	public SkillFactoryDbHelper(Context context) {
		super(context, TABLE_NAME, null, DATABASE_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		//db.execSQL(TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
	}
	
	public void openDatabase(){
		try{
			database = SQLiteDatabase.openDatabase("", null, SQLiteDatabase.OPEN_READONLY);
		}catch(SQLException e){
			Log.wtf("Character Sheet", "Skill Database : Could not open database");
		}
	}
	
	@Override 
	public synchronized void close(){
		if (database != null){
			database.close();
		}
		super.close();
	}
	
	private boolean checkDatabase(){
		SQLiteDatabase db = null;
		try{
			db = SQLiteDatabase.openDatabase("", null, SQLiteDatabase.OPEN_READONLY);
		}catch(SQLiteException e){
			
		}
		if (db != null){
			db.close();
		}
		return db != null;
	}
	
	public void createDatabase() throws IOException{
		if (checkDatabase()){
			
		}else{
			this.getReadableDatabase();
			try{
				copyDatabase();
			}catch(IOException e){
				throw new IOException("Error Copying database");
			}
		}
	}
	
	private void copyDatabase() throws IOException{
		InputStream input = context.getAssets().open("");
		OutputStream myOutput = new FileOutputStream("");
		
		byte[] buffer = new byte[1024];
    	int length;
    	while ((length = input.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	input.close();
	}
	
}
